<template>
	<div class="question-management">
		<el-card class="box-card">
			<template #header>
				<div class="card-header">
					<span>试题信息管理</span>
					<el-button @click="handleSelectAll" type="primary">全部选中</el-button>
					<el-button @click="handleClearSelection" type="success">全部取消</el-button>
					<el-button @click="handleAdd" type="warning">添加标签</el-button>
				</div>
			</template>

			<!-- 搜索框 -->
			<div class="search-container">
				<!-- 标签名称输入框 -->
				<el-input v-model="searchParams.name" placeholder="请输入标签名称" clearable
					style="width: 200px; margin-right: 10px" />
			
				<!-- 学科名称输入框 -->
				<el-select v-model="searchParams.subject" filterable placeholder="选择学科信息" style="width: 150px">
					<el-option v-for="item in subjects" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
				
				<!-- 标签名称输入框 -->
				<el-select v-model="searchParams.label" filterable placeholder="选择标签信息" style="width: 150px">
					<el-option v-for="item in labels" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			
				<!-- 是否审核下拉列表 -->
				<el-select v-model="searchParams.is_access" placeholder="请选择审核状态" clearable
					style="width: 200px; margin-right: 10px">
					<el-option label="已审核" :value="true" />
					<el-option label="未审核" :value="false" />
				</el-select>
			
				<!-- 创建时间范围选择器 -->
				<el-date-picker v-model="searchParams.created_time_range" type="datetimerange" range-separator="至"
					start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss"
					style="width: 300px; margin-right: 10px" />
			
				<!-- 搜索按钮 -->
				<el-button type="primary" @click="handleSearch">搜索</el-button>
			</div>

			<!-- 试题列表表格 -->
			<el-table ref="tableRef" :data="paginatedQuestions" style="width: 100%" border height="400"
				@selection-change="handleSelectionChange">
				<!-- 选择列 -->
				<el-table-column type="selection" width="55" align="center"/>
				
				<!-- 序号列 -->
				<el-table-column type="index" label="序" width="55" align="center" />

				<!-- 试题ID列 -->
				<el-table-column prop="id" label="ID" width="100" show-overflow-tooltip align="center"/>

				<!-- 题型列 -->
				<el-table-column prop="_type" label="题型" show-overflow-tooltip align="center"/>

				<!-- 难度列 -->
				<el-table-column prop="level" label="难度" show-overflow-tooltip align="center"/>
				
				<!-- 试题题干列 -->
				<el-table-column prop="title" label="题干" show-overflow-tooltip align="center"/>
				
				<!-- 试题选项列 -->
				<el-table-column prop="options" label="选项" show-overflow-tooltip align="center"/>
				
				<!-- 试题答案列 -->
				<el-table-column prop="answer" label="答案" show-overflow-tooltip align="center"/>
				
				<!-- 是否审核列 -->
				<el-table-column prop="is_access" label="是否审核" show-overflow-tooltip align="center" />
				
				<!-- 创建时间列 -->
				<el-table-column prop="created_time" label="创建时间" show-overflow-tooltip align="center" />

				<!-- 操作列（固定右侧） -->
				<el-table-column label="操作" width="180" fixed="right">
					<template #default="scope">
						<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
						<el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页 -->
			<el-pagination style="margin-top: 20px;" background layout="total, sizes, prev, pager, next, jumper"
				:total="pageTotal" :page-size="pageSize" :current-page="currentPage" :page-sizes="[5, 10, 20, 50]"
				@current-change="handlePageChange" @size-change="handleSizeChange" />
		</el-card>

		<!-- 添加/编辑试题对话框 -->
		<el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
			<el-form :model="form" label-width="80px" ref="ruleFormRef" :rules="rules">
				<el-form-item label="试题题干">
					<el-input v-model="form.content" type="textarea" />
				</el-form-item>
				<el-form-item label="题型">
					<el-select v-model="form._type" placeholder="请选择题型">
						<el-option label="单选题" value="单选题" />
						<el-option label="多选题" value="多选题" />
						<el-option label="判断题" value="判断题" />
					</el-select>
				</el-form-item>
				<el-form-item label="难度">
					<el-select v-model="form.level" placeholder="请选择难度">
						<el-option label="简单" value="简单" />
						<el-option label="中等" value="中等" />
						<el-option label="困难" value="困难" />
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleSubmit">提交</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
	import { ref, nextTick, computed, onMounted, reactive } from 'vue';
	import { ElMessageBox, ElTable, ElMessage } from 'element-plus';
	import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
	import type { Subject, Label, Question, QuestionType, QuestionLevel, ResErrorData } from '@/common/interfaces.ts'
	import { myElMessage } from '@/common/my_ele.ts'
	import {
		fetchQuestions,
		addQuestion,
		updateQuestion,
		deleteQuestion,
		searchPaginationQuestion,
	} from '@/apis/question';
	import { fetchSubjects } from '@/apis/subject'
	import { fetchLabels } from '@/apis/label'
	import { fetchQuestionTypes } from '@/apis/questionType'
	import { fetchQuestionLevels } from '@/apis/questionLevel'

	// 学科数据
	const subjects = ref<Subject[]>([]);
	// 标签数据
	const labels = ref<Label[]>([]);
	// 题型数据
	const questionTypes = ref<QuestionType[]>([]);
	// 难度水平数据
	const questionLevels = ref<QuestionLevel[]>([]);

	// 试题数据
	const questions = ref<Question[]>([]);

	// 搜索关键词
	const searchKeyword = ref('');
	// 搜索参数
	const searchParams = ref({
		subject: null,
		title: "", // 标签名称
		is_access: undefined, // 是否审核
		created_time_range: [], // 创建时间范围
	});

	// 分页相关
	const pageTotal = ref(1); // 总页数
	const pageSize = ref(5); // 每页显示条数
	const currentPage = ref(1); // 当前页码

	// 对话框状态
	const dialogVisible = ref(false);
	const dialogTitle = ref('');

	// 表单数据
	const form = ref<Question>({
		id: null,
		subject: null,
		title: '',
		is_access: false,
	});
	
	const rules = {
		name: [
			{ required: true, message: '名称不能为空', trigger: 'blur' },
		],
		//  age: [
		// { required: true, message: '年龄不能为空', trigger: 'blur' },
		// { type: 'number', message: '年龄必须为数字', trigger: 'blur' },
		//  ],
	};
	const ruleFormRef = ref<FormInstance>();

	// 当前操作类型（添加或编辑）
	const isEditing = ref(false);

	// 选中的行数据
	const selectedRows = ref<Question[]>([]);

	// 获取表格组件的引用
	const tableRef = ref<InstanceType<typeof ElTable>>();

	// 过滤后的试题列表（根据搜索关键词）
	const filteredQuestions = computed(() => {
		return questions.value.filter((question) =>
			question.title.includes(searchKeyword.value)
		);
	});
	
	// 处理搜索
	const handleSearch = async () => {
		try {
			fetchData();
		} catch (error) {
			console.error("搜索失败:", error);
		}
	};

	// 分页后的试题列表
	const paginatedQuestions = computed(() => {
		// const start = (currentPage.value - 1) * pageSize.value;
		// const end = start + pageSize.value;
		// return filteredQuestions.value.slice(start, end);
		return filteredQuestions.value
	});

	// 获取标签数据
	const fetchData = async () => {
		try {
			// labels.value = await fetchLabels();
			await searchPaginationQuestion(pageSize.value, currentPage.value, searchParams.value)
				.then(res => {
					// console.log('正常：\n', res);
					questions.value = res.data.results;
					pageTotal.value = res.data.count;
				})
				.catch(err => {
					console.log("错误：\n", err)
				})
		} catch (error) {
			console.error('获取标签数据失败:', error);
		}
	};

	// 打开添加试题对话框
	const handleAdd = () => {
		dialogTitle.value = '添加试题';
		form.value = { id: null, content: '', type: '', level: '' };
		isEditing.value = false;
		dialogVisible.value = true;
	};

	// 打开编辑试题对话框
	const handleEdit = (row : Question) => {
		dialogTitle.value = '编辑试题';
		form.value = { ...row };
		isEditing.value = true;
		dialogVisible.value = true;
	};

	// 提交表单（添加或编辑）
	const handleSubmit = async (formEl : FormInstance | undefined) => {
		if (!formEl) return
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				if (isEditing.value) {
					if (form.value.id) {
						// 编辑标签
						await updateQuestion(form.value.id, form.value)
							.then(res => {
								if (res.status === 200) {
									ElMessage({
										message: `更新成功`,
										type: 'success',
										duration: 3000,
									})
								}
							})
							.catch(err => {
								console.log("更新发生错误：\n", err);
							})
					}
				} else {
					// 添加学科
					await addQuestion(form.value)
						.then(res => {
							if (res.status === 201) {
								ElMessage({
									message: `新建成功`,
									type: 'success',
									duration: 3000,
								})
							}
						})
						.catch(err => {
							if (err.status === 400) {
								myElMessage(err.response.data, 'error')
							}
						})
				}
				dialogVisible.value = false;
				fetchData(); // 重新获取数据
			} else {
				ElMessage({
					message: `提交的信息不能为空:${fields}`,
					type: 'error',
				})
			}
		})
	};

	// 删除试题
	const handleDelete = async (row : Label) => {
		try {
			// 弹出确认框
			await ElMessageBox.confirm('确定要删除该试题吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			});
			if (row.id) {
				// 用户确认后执行删除
				await deleteQuestion(row.id)
					.then(res => {
						if (res.status === 204) {
							ElMessage({
								message: `删除成功`,
								type: 'success',
								duration: 3000,
							})
							fetchData(); // 重新获取数据
						}
					})
					.catch(err => {
						console.log("删除发生错误：\n", err);
					})
			}
		} catch (error) {
			if (error == 'cancel') { // 取消便不用提醒
				// console.error('删除失败:', error);
			}
		}
	};

	// 处理分页变化
	const handlePageChange = async (page : number) => {
		currentPage.value = page;
		await nextTick(); // 等待 DOM 更新完成
		// 重新获取数据
		fetchData();
	};
	
	// 处理每页条数变化
	const handleSizeChange = (size : number) => {
		pageSize.value = size;
		currentPage.value = 1; // 每页条数变化时重置到第一页
		fetchData();
	};
	
	// 处理选中行变化
	const handleSelectionChange = (rows : Label[]) => {
		selectedRows.value = rows;
	};
	
	// 全部选中
	const handleSelectAll = () => {
		if (tableRef.value) {
			tableRef.value.toggleAllSelection();
		}
	};
	
	// 全部取消
	const handleClearSelection = () => {
		if (tableRef.value) {
			tableRef.value.clearSelection();
		}
	};
	
	// 组件挂载时获取数据
	onMounted(() => {
		fetchData();
		// fetchSubjects()
		// 	.then(res => {
		// 		console.log("学科数据：\n", res);
		// 		subjects.value = res.data.results;
		// 	})
	});
</script>

<style scoped>
	.question-management {
		padding: 20px;
	}
	
	.search-container {
		display: flex;
		align-items: center;
		padding: 20px;
		background-color: #f5f5f5;
		border-radius: 4px;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
</style>